package com.heima.aspect;

import com.heima.anno.AutoFill;

import com.heima.config.BaseContext;
import com.heima.enu.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* com.heima.mapper..*.*(..))&& @annotation(com.heima.anno.AutoFill)")
    public void pointCut(){}

    @Before("pointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行公共字段自动填充");
        //获取方法签名对象
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        //获取方法注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //获取方法上的注解对象
        OperationType operationType = autoFill.value();
        //获取参数
        Object[] args = joinPoint.getArgs();
        //判断参数不为空
        if(args == null || args.length == 0){
            return;
        }
        Object entity = args[0];
        //准备填充的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //根据不同类型进行赋值
        if (operationType == OperationType.INSERT){
            //根据反射赋值
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                //Method setCreateUser = entity.getClass().getDeclaredMethod("setCreateUser", Long.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setCreateTime.invoke(entity, now);
                //setCreateUser.invoke(entity, currentId);
                setUpdateTime.invoke(entity, now);
                //setUpdateUser.invoke(entity, currentId);
            } catch (Exception e) {
                log.error("自动填充失败");
            }
        }else if (operationType== OperationType.UPDATE){
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                //Method setUpdateUser = entity.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateTime.invoke(entity, now);
                //setUpdateUser.invoke(entity, currentId);
            } catch (Exception e) {
                log.error("自动填充失败");
            }
        }
    }
}
